#include "server.h"
#include "Log.h"

#include "GlobalFeature_API.h"

int server::thread_func(){
	LOG_INFO_VA("[%s] server going to start listen ip: %s port: %s, DEALER ip: %s port: %s!", get_name().c_str(), get_front_address().get_ip().c_str(), get_front_address().get_port().c_str(), get_back_address().get_ip().c_str(), get_back_address().get_port().c_str());
	int ret = 0;

	_zmq = zmq_ctx_new();
	if(_zmq == NULL){
		LOG_ERROR_VA("zmq ERROR");
		return -1;
	}
	_zmq_front = zmq_socket(_zmq, ZMQ_ROUTER);
	if(_zmq_front == NULL){
		LOG_ERROR_VA("zmq front socket ERROR");
		return -1;
	}
	//ret = zmq_bind(_zmq_front, "tcp://*:45500");
	string front_tcp_addr = "tcp://*:";
	front_tcp_addr.append(get_front_address().get_port());
	ret = zmq_bind(_zmq_front, front_tcp_addr.c_str());
	if(ret == -1){
		LOG_ERROR_VA("zmq front bind ERROR");
		return -1;
	}

	_zmq_back = zmq_socket(_zmq, ZMQ_DEALER);
	if(_zmq_back == NULL){
		LOG_ERROR_VA("zmq back socket ERROR");
		return -1;
	}
	//ret = zmq_bind(_zmq_back, "inproc://workers");
	string back_tcp_addr = "tcp://*:";
	back_tcp_addr.append(get_back_address().get_port());
	ret = zmq_bind(_zmq_back, back_tcp_addr.c_str());
	if(ret == -1){
		LOG_ERROR_VA("zmq back bind ERROR");
		return -1;
	}

//	int timeout = 1500;
//	int zmq_hwm = 1;
//	zmq_setsockopt(_zmq_rep, ZMQ_SNDHWM, &zmq_hwm, sizeof(zmq_hwm));
//	zmq_setsockopt(_zmq_rep, ZMQ_SNDTIMEO, &timeout, sizeof(timeout));
//	zmq_setsockopt(_zmq_rep, ZMQ_RCVTIMEO, &timeout, sizeof(timeout));

	//_thread_pool = new thread_pool;
	_thread_pool->set_server(this);
	LOG_INFO_VA("[%s] thread pool start!", get_name().c_str());
	_thread_pool->start();
	LOG_INFO_VA("[%s] server started listen ip: %s port: %s, DEALER ip: %s port: %s!", get_name().c_str(), get_front_address().get_ip().c_str(), get_front_address().get_port().c_str(), get_back_address().get_ip().c_str(), get_back_address().get_port().c_str());

	zmq_proxy(_zmq_front, _zmq_back, NULL);

	zmq_close(_zmq_back);
	zmq_close(_zmq_front);
	zmq_ctx_destroy(_zmq);
	return 0;
}



